import struct

import errorhandle

SINGLE_PACK_SIZE = 18
REBAR_RANGE = 4
REBAR_DIAMETER = REBAR_RANGE + 2
DV_VOLTAGE = REBAR_DIAMETER + 4
DV_NOW_THICKNESS = DV_VOLTAGE + 2
DV_REAL_THICKNESS = DV_NOW_THICKNESS + 2
SHIFT = DV_REAL_THICKNESS + 2
HEADER = b'\xaa\xaa'


def parse_rebar_data(data):
    # self.rebar.clear()
    rebar = []
    if len(data) != SINGLE_PACK_SIZE:
        return errorhandle.REBAR_LENGTH_EXCEPTION
    if data[0:2] != HEADER:
        return errorhandle.REBAR_HEADER_EXCEPTION

    temp = struct.unpack('b'*(REBAR_RANGE-2), data[2:REBAR_RANGE])
    rebarRange = temp[0] * 256 + temp[1]

    temp = struct.unpack('b'*(REBAR_DIAMETER-REBAR_RANGE), data[REBAR_RANGE:REBAR_DIAMETER])
    rebarDiameter = temp[0] * 256 + temp[1]

    temp = struct.unpack('B'*(DV_VOLTAGE-REBAR_DIAMETER), data[REBAR_DIAMETER:DV_VOLTAGE])
    voltage = temp[0] * (256**3) + temp[1] * (256**2) + temp[2] * 256 + temp[3]

    temp = struct.unpack('B'*(DV_NOW_THICKNESS-DV_VOLTAGE), data[DV_VOLTAGE:DV_NOW_THICKNESS])
    currThickness = temp[0] * 256 + temp[1]

    temp = struct.unpack('B'*(DV_REAL_THICKNESS-DV_NOW_THICKNESS), data[DV_NOW_THICKNESS:DV_REAL_THICKNESS])
    realThickness = temp[0] * 256 + temp[1]

    temp = struct.unpack('b', data[SHIFT-2:SHIFT-1])
    shift = float(temp[0] * 256)
    temp = struct.unpack('B', data[SHIFT-1:SHIFT])
    shift = (shift + temp[0])/10

    rebar.extend([rebarRange, rebarDiameter, voltage, currThickness, realThickness, shift])
    # print("Parser rebar get: " + str(rebar))
    return rebar


class RebarParser:
    pass



# exp1 = b'\xaa\xaa\x00\x00\x00\n\x00\x00\x07\x1c\x00\x00\x00F\x01\xe6\r\n'
# exp2 = b'\xaa\xaa\x00\x00\x00\n\x00\x00\x07j\x00\x00\x00F\x01\xe6\r\n'
# exp3 = b'\xaa\xaa\x00\x00\x00\n\x00\x00\x07\x87\x00\x00\x00F\x01\xe6\r\n'
#
# a = RebarParser()
#
# a.parse_rebar_data(exp1)
# a.parse_rebar_data(exp2)
# a.parse_rebar_data(exp3)